const _ = require("lodash");
import { Buffer } from 'buffer';
import {MeterQueryType} from "./SerialCommon";
import {smartMeterConf} from "./smartMeterConf";


export function parserSmartMeter(meterList) {
    console.log("parserSmartMeter: ", meterList);
    let real_time = {};
    let stat = {};
    for (let item of meterList) {
        if(!item.buff || item.buff.length <= 0) {
            continue;
        }
        let buffer = Buffer.from(item.buff);
        //在conf中找对应的conf文件，如果能找到，则对数据进行处理
        let find = _.find(smartMeterConf, { address: item.address });
        if (!find) {
            continue;
        }
        //如果是实时数据
        if (find.type == MeterQueryType.REALTIME) {
            for (let property of find.properties) {
                //新增对象
                real_time[property] = (real_time[property] && real_time[property].length) ? real_time[property] : [];
            }
            let obj = new Object();
            for (let temp of find.conf) {
                switch (temp.type) {
                    case 1:
                        obj[temp.name] = buffer.readFloatLE(temp.position).toFixed(2);
                        break;
                }
                if (temp.is_end) {
                    obj.channel = find.channel;
                    real_time[temp.parent] = _.concat(real_time[temp.parent], obj);
                    obj = new Object();
                }
            }
        } else if (find.type == MeterQueryType.STAT) {
            //如果是统计数据
            for (let property of find.properties) {
                //新增对象，先让数据中有这个空的对象
                stat[property] = (stat[property] && stat[property].length) ? real_time[property] : [];
            }
            //用于存放每一个channel的数据
            let obj = new Object();
            for (let temp of find.conf) {
                switch (temp.type) {
                    case 1:
                        obj[temp.name] = {};
                        obj[temp.name].value = buffer.readFloatLE(temp.position).toFixed(2);
                        obj[temp.name].time = buffer.readUInt16LE(temp.position + 2) + "-" + buffer.readUInt16LE(temp.position + 3) + buffer.readUInt16LE(temp.position + 4);
                        break;
                }
                if (temp.is_end) {
                    obj.channel = find.channel;
                    stat[temp.parent] = _.concat(stat[temp.parent], obj);
                    obj = new Object();
                }
            }
        }
    }
    console.log("realtime: ", real_time);
    console.log("stat: ", stat);
    return {"realtime": real_time, "stat": stat};
}